<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import Sidebar from '../components/Sidebar.vue'

type Agent = {
  id: number;
  name: string;
  description: string;
  avatarUrl: string;
  compatibleSources: string;
};

const router = useRouter()
const agents = ref<Agent[]>([]);
const isModalOpen = ref(false);
const modalTitle = ref('');

const initialAgent: Agent = { id: 0, name: '', description: '', avatarUrl: '', compatibleSources: '' };
let activeAgent = reactive<Agent>({ ...initialAgent });


const fetchAgents = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/agents', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    agents.value = await response.json();
  } catch (error) {
    console.error("Failed to fetch agents:", error);
    // 在这里可以添加一些用户友好的错误提示, e.g., using a toast notification library
  }
};

onMounted(fetchAgents);

const goBack = () => {
  router.back()
}

const editAgent = (id: number) => {
  // TODO: 实现编辑逻辑，例如跳转到编辑页面或打开模态框
  console.log(`Editing agent ${id}`);
};

const deleteAgent = async (id: number) => {
  if (!window.confirm('您确定要删除这个智能体吗？此操作无法撤销。')) {
    return;
  }

  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/agents/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (!response.ok) {
      // 如果后端返回错误信息，可以尝试解析并显示
      const errorData = await response.json().catch(() => ({ message: '删除智能体失败。' }));
      throw new Error(errorData.message);
    }
    // 从UI中移除
    agents.value = agents.value.filter(agent => agent.id !== id);
  } catch (error) {
    console.error("Deletion failed:", error);
    alert(`错误: ${error}`);
  }
};

const createAgent = () => {
    // TODO: 实现创建新Agent的逻辑
    console.log("Navigating to create new agent page...");
}

</script>

<template>
  <div class="agent-management-page bg-[var(--secondary-color)] min-h-screen">
    <div class="flex h-full grow">
      <!-- 使用统一的侧边栏组件 -->
      <Sidebar />

      <!-- 主内容区域 -->
      <main class="ml-72 flex-1 p-8">
        <div class="max-w-7xl mx-auto">

          <!-- 页面头部 -->
          <header class="flex items-center justify-between mb-8">
            <div class="flex items-center gap-4">
              <button @click="goBack" class="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
              </button>
              <h1 class="text-3xl font-bold text-[var(--text-primary)]">智能体管理</h1>
            </div>
            <button @click="createAgent" class="inline-flex items-center justify-center px-4 py-2.5 text-sm font-semibold rounded-lg bg-[var(--primary-color)] text-[var(--text-primary)] hover:bg-opacity-80 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--primary-color)] transition-colors duration-150">
              <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
              创建新智能体
            </button>
          </header>

          <!-- Agent列表 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="agent in agents" :key="agent.id" class="bg-white rounded-lg shadow-md hover:shadow-xl transition-shadow duration-300 overflow-hidden border border-[var(--border-color)]">
              <div class="p-5">
                <div class="flex items-start gap-4">
                  <img :src="agent.avatarUrl" alt="Agent Avatar" class="w-20 h-20 rounded-lg object-cover border-2 border-[var(--border-color)]">
                  <div class="flex-1">
                    <h2 class="text-lg font-semibold text-[var(--text-primary)]">{{ agent.name }}</h2>
                    <p class="text-sm text-[var(--text-secondary)] mt-1">{{ agent.description }}</p>
                  </div>
                </div>
                <div class="mt-4 pt-4 border-t border-[var(--border-color)]">
                    <p class="text-xs text-[var(--text-secondary)]">
                      <span class="font-medium text-[var(--text-primary)]">兼容数据源:</span>
                      {{ agent.compatibleSources }}
                    </p>
                </div>
              </div>
              <div class="bg-[var(--secondary-color)] px-5 py-3 flex justify-end gap-3">
                <button @click="editAgent(agent.id)" class="px-3 py-1 text-xs font-medium text-[var(--text-primary)] bg-white rounded-md border border-[var(--border-color)] hover:bg-gray-50 transition-colors">编辑</button>
                <button @click="deleteAgent(agent.id)" class="px-3 py-1 text-xs font-medium text-red-600 bg-red-50 rounded-md border border-red-200 hover:bg-red-100 transition-colors">删除</button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<style>
/* 共享样式可以定义在 main.css 中，这里只放该页面特定的样式 */
.agent-management-page {
  --primary-color: #dce8f3;
  --secondary-color: #f1f2f4;
  --text-primary: #121416;
  --text-secondary: #6a7681;
  --border-color: #dde1e3;
}
</style> 